import { Component, OnInit, ChangeDetectionStrategy, OnDestroy } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Router } from '@angular/router'
import { AppStateService } from './service/app-state.service'
import { NavState } from './common/const/nav-state.const'
import { AppJWTService } from './service/app-jwt.service'
import { AppMessageDialogService } from './service/app-message-dialog.service'
import { AppScreenService } from './service/app-screen.service'
import { distinctUntilChanged, debounceTime } from 'rxjs/operators'
import { AppSnackBarService } from './common/snack-bar/snack-bar.service'

@Component({
  // appJwtservice get 方法值出现更新，使用仅检查一次跳过报错OnPush
  changeDetection: ChangeDetectionStrategy.Default,
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit, OnDestroy {
  title = '党务管理系统'
  navState = NavState

  constructor(
    private appJwtService: AppJWTService,
    private screenService: AppScreenService,
    public appStateService: AppStateService,
    private messageService: AppMessageDialogService,
    private snackBarService: AppSnackBarService,
    private router: Router,
  ) {
    router.onSameUrlNavigation = 'reload'
  }

  ngOnInit(): void {
    this.listenScreen()
    this.appJwtService.isAuthenticated()
      .subscribe(next => {
        if (next) {
          // console.log(`Subject:${this.appJwtService.subject}`)
          // this.bottomSheetService.show()
          this.snackBarService.openLeftBottom('你已登录', '消息')
        }
        this.appStateService.navState =
          next ? NavState.NORMAL : NavState.ANONYMOUS
      },
        () => {
          this.messageService.showMessage('凭据失效', '请重新登录')
          this.router.navigate(['login'])
        }
      )
  }

  getNavState(): String {
    return this.appStateService.navState
  }

  ngOnDestroy(): void {
    this.screenService.screenLevel$.unsubscribe()
  }

  listenScreen() {
    // 监听 屏幕变化
    this.screenService.screenLevel$
      .pipe(
        distinctUntilChanged(),
        debounceTime(200))
      .subscribe((level) => {
        console.log(`screen level update: ${level}`)
      })
  }
}
